<template>
    <div>
        <vheader :ismini="iscollapse"></vheader>
        <el-container class="content_main" style="border:0px solid #e3e3;">
            <el-main >
                <el-row>
                    <el-col :span="22" :xs="22" :sm="22" :md="22" :lg="22" :xl="22" :push="1" :pull="1">
                        <el-steps :active="2" simple >
                            <el-step title="新增主题" icon="el-icon-edit"></el-step>
                            <el-step title="新增产品" icon="el-icon-picture"></el-step>
                            <el-step title="新增（关联）属性" icon="el-icon-upload"></el-step>
                        </el-steps>
                    </el-col>
                    <el-col :span="22" :xs="22" :sm="22" :md="22" :lg="22" :xl="22" :push="1" :pull="1">
                        <el-row :gutter="40">
                           <el-col :span="5" :xs="5" :sm="5" :md="5" :lg="5" :xl="5" class="pageleft" >
                                <div class="grid-content bg-purple">
                                    <h3>一级节点</h3>
                                    <el-input
                                      placeholder="输入关键字进行过滤"
                                      v-model="filterText">
                                    </el-input>

                                    <el-tree
                                      class="filter-tree"
                                      :data="subject_tree_data"
                                      :props="defaultProps"
                                      default-expand-all
                                      :filter-node-method="filterNode"
                                      @node-click="handleNodeClick"
                                      ref="tree">
                                    </el-tree>
                                </div>
                            </el-col>
                            <el-col :span="19"  :xs="19" :sm="19" :md="19" :lg="19" :xl="19"  class="pageleft" >
                                <el-row :gutter="12" style="border:0px solid red;">
                                    <el-col :span="23" :push="1" >
                                        <h3>新增属性节点</h3>
                                        <el-card style="margin-top:20px;text-align: right;">
                                            <span>这里得说点什么</span>
                                            <el-button type="success" @click="onSubmit" size="mini">提交</el-button>
                                        </el-card>
                                        <el-card v-for="(item,index) in form.addlist"  style="margin-top:10px;">
                                            <el-form ref="form" :inline="true" label-width="60px" size="mini">
                                                <el-form-item label="上级">
                                                    <el-input v-model="item.ParentName" readonly="readonly" placeholder="一级节点"></el-input>
                                                </el-form-item>
                                                <el-form-item label="名称">
                                                    <el-input v-model="item.FullName"></el-input>
                                                </el-form-item>
                                                <el-form-item label="简称">
                                                    <el-input v-model="item.ShortName" ></el-input>
                                                </el-form-item>
                                                
                                                <el-form-item label="标签">
                                                    <el-checkbox-group v-model="item.tags">
                                                    <el-checkbox :label="tag" :key="tag" v-for="tag in baseDate.Taglist" name="type"></el-checkbox>
                                                    </el-checkbox-group>
                                                </el-form-item>
                                                <el-form-item>
                                                    <el-button type="success" size="mini"  :index="index" @click="onSubmit($event)" icon="el-icon-success" circle></el-button>
                                                    <el-button type="primary" size="mini"  :index="index" @click="onAddRow($event)" icon="el-icon-edit" circle></el-button>
                                                    <el-button type="danger" size="mini" :itemkey="0"  :index="index" @click="onDeleteRow($event,1)" icon="el-icon-delete" circle></el-button>
                                                </el-form-item>
                                                <el-form-item label="说明">
                                                    <el-input type="textarea" v-model="item.Content" style="width:750px;"></el-input>
                                                </el-form-item>
                                            </el-form>
                                        </el-card>
                                        <el-card v-for="(item,index) in form.editlist"  style="margin-top:10px;">
                                            <el-form ref="form" :inline="true" label-width="60px" size="mini">
                                                <el-form-item label="上级">
                                                    <el-input v-model="item.ParentName" readonly="readonly" placeholder="一级节点"></el-input>
                                                </el-form-item>
                                                <el-form-item label="名称">
                                                    <el-input v-model="item.FullName"></el-input>
                                                </el-form-item>
                                                <el-form-item label="简称">
                                                    <el-input v-model="item.ShortName" ></el-input>
                                                </el-form-item>
                                                
                                                <el-form-item label="标签">
                                                    <el-checkbox-group v-model="item.tags">
                                                    <el-checkbox :label="tag" :key="tag" v-for="tag in baseDate.Taglist" name="type"></el-checkbox>
                                                    </el-checkbox-group>
                                                </el-form-item>
                                                <el-form-item>
                                                    <el-button type="success" size="mini"  :index="index" @click="onSubmit($event)" icon="el-icon-success" circle></el-button>
                                                    <el-button type="primary" size="mini"  :index="index" @click="onAddRow($event)" icon="el-icon-edit" circle></el-button>
                                                    <el-button type="danger" size="mini" :itemkey="item.Id" :index="index" @click="onDeleteRow($event,2)" icon="el-icon-delete" circle></el-button>
                                                </el-form-item>
                                                <el-form-item label="说明">
                                                    <el-input type="textarea" v-model="item.Content" style="width:750px;"></el-input>
                                                </el-form-item>
                                            </el-form>
                                        </el-card>
                                    </el-col>
                                    
                                </el-row>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
            </el-main>
        </el-container>
    </div>
</template>

<script>
import vheader from "../common/Header";
import vfooter from "../common/Footer";
import { SubjectType, Tag, page, page_rule } from "../../data/base_data";
import { baseUrl, routerMode, baseImgPath } from "../../config/env";

export default {
  data() {
    return {
      iscollapse: false,
      isshowfooter: false,
      key: "",
      subjectlist: [],
      filterText:"",
      subject_tree_data:[],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      baseDate: {
        SubjectTypelist: [],
        Taglist: [],
        curpage: {}
      },
      loadData: {
        firstAttributeNodes: []
      },
      form: {
        SubjectID: 0,
        editlist: [],
        addlist: []
      },
    };
  },
  watch: {
    "form.SubjectType": function(b, a) {
      this.$nextTick(function() {
        //加载对应主题得属性
        alert(b + ":" + a);
      });
    },
    $route: "fetchData", 
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  computed: {
    firstAttributeNodes: function() {
      var templist1 = this.form.addlist.select(s => {
        return (
          s.ParentName &&
          s.ParentID &&
          s.Id &&
          s.ParentName != "" &&
          s.ParentID != 0 &&
          s.Id != 0
        );
      });
      var templist2 = this.form.editlist.select(s => {
        return (
          s.ParentName &&
          s.ParentID &&
          s.Id &&
          s.ParentName != "" &&
          s.ParentID != 0 &&
          s.Id != 0
        );
      });
      var newlist = [];
      templist1.forEach(element => {
        if (element) newlist.push(element);
      });
      templist2.forEach(element => {
        if (element) newlist.push(element);
      });
      return newlist;
    }
  },
  methods: {
    fetchData: function() {
      this.form.SubjectID = this.$route.params.sid;
      this.loadSubjectAttribute();
    },
    //树点击节点
    filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      console.log(data);
    },
    loadSubjectAttributeTreeData : function(datalist, pid) {
       var list = datalist.where(function(item){
          return item.ParentID == pid
       });
       for(var i =0; i < list.length; i++) {
          var attr_item = list[i];
          var treeNode = {
            id: attr_item.Id,
            label: attr_item.FullName
          };
          treeNode.children = this.loadSubjectAttributeTreeData(datalist, treeNode.Id);
          this.subject_tree_data.push(treeNode);
       }
    },
    loadSubjectAttribute: function() {
      // var rule =  {
      //     Field: "SubjectID",
      //     Value: this.form.SubjectID,
      //     Operate: 3
      // }
      // this.baseDate.curpage.FilterGroup.Rules = [rule];
      //post数据
      this.$http
        .post(baseUrl + "api/Admin/ContrastAttribute/GetSubjectAttribute", [
          this.form.SubjectID
        ])
        .then(
          function(res) {
            if (res.body.Rows.length > 0) {
              for (let index = 0; index < res.body.Rows.length; index++) {
                const element = res.body.Rows[index];
                element.tags = element.Tag ? element.Tag.split(",") : [];
                this.form.editlist.push(element);
              }
              this.loadSubjectAttributeTreeData(this.form.editlist, 0);
            } else this.onAddRow();
          },
          function(res) {
            alert("操作数据获取失败");
          }
        );
    },
    onSubmit: function() {
      //post数据
      var that = this;
      this.form.addlist.forEach(el => {
        el.Tag = el.tags ? el.tags.join(",") : "";
        el.SubjectID = that.form.SubjectID;
        delete el["tags"];
      });
      this.form.editlist.forEach(el => {
        el.Tag = el.tags ? el.tags.join(",") : "";
        el.SubjectID = that.form.SubjectID;
        delete el["tags"];
      });
      var pushlist = this.form.addlist.concat(this.form.editlist);
      this.$http
        .post(baseUrl + "api/Admin/ContrastAttribute/CreateAndUpdate", pushlist)
        .then(
          function(res) {
            if (res.body.Type == 200 || res.body.Type == 203) {
              this.$message({
                message: "【" + this.form.FullName + "】" + res.body.Content,
                type: "success"
              });
              var sid = this.form.SubjectID;
              this.$router.push({ path: `/contentshow/${sid}/0` }); // -> /user/123
            }
          },
          function(res) {
            alert("error:" + res.status);
          }
        );
    },
    onAddRow: function() {
      var currentNode = this.$refs.tree.getCurrentNode();
      this.form.addlist.unshift({
        SubjectID: this.SubjectID,
        FullName: "",
        ShortName: "",
        ParentID: currentNode!=null?currentNode.id:"",
        ParentName:currentNode!=null?currentNode.label:"",
        EnName: "",
        Tag: "",
        tags: [],
        Remark: "",
        Resume: "",
        CreateTime: ""
      });
    },
    onDeleteRow: function(e, t) {
      if (t == 1)
        this.form.addlist.splice(
          parseInt(e.currentTarget.getAttribute("index")),
          1
        );
      else {
        this.$confirm("此操作将永久删除该条记录, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          //这里需要加上询问
          this.$http
            .post(baseUrl + "api/Admin/ContrastAttribute/Delete", [
              e.currentTarget.getAttribute("itemkey")
            ])
            .then(
              function(res) {
                if (res.body.Type == 200 || res.body.Type == 203) {
                  this.$message({
                    message: "删除成功",
                    type: "success"
                  });
                  this.form.editlist.splice(
                    parseInt(e.currentTarget.getAttribute("index")),
                    1
                  );
                }
              },
              function(res) {
                alert("error:" + res.status);
              }
            );
        });
      }
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
    }
  },
  mounted: function() {
    let self = this;
    window.onresize = function() {
      self.clientHeight =
        document.documentElement.clientHeight - (this.isshowfooter ? 200 : 150);
      self.clientWidth = document.documentElement.clientWidth;
      $("#content_module").height(self.clientHeight);
      $(".pageleft").height(self.clientHeight - 20);
      //获取宽度
      self.iscollapse = self.clientWidth < 768;
    };
    window.onresize();
  },
  created() {
    this.baseDate.SubjectTypelist = SubjectType;
    this.baseDate.Taglist = Tag;
    this.baseDate.curpage = page;
    this.fetchData();
  },
  components: {
    vheader,
    vfooter
  }
};
</script>
<style scoped>
#content_module {
  width: 100%;
  padding: 0;
  margin: 0 auto;
}
.content_main {
  width: 1300px;
  padding: 0;
  margin: 0 auto;
  margin-top: 10px;
}
.pageleft {
  overflow: hidden;
  overflow-y: auto;
}
.el-col {
  border-radius: 4px;
}
</style>
